package org.example.petsystem.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.petsystem.entity.Messages;
import org.example.petsystem.entity.ResultBody;
import org.example.petsystem.mapper.MessageMapper;
import org.example.petsystem.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public ResultBody getMessageList(Map<String,Object> map) {
        String currentUserPhone = map.get("phone").toString();
        List<Messages> messages = messageMapper.getMessageList(currentUserPhone);
        
        if(!messages.isEmpty()) {
            // 按对话对象分组
            Map<String, List<Messages>> groupedMessages = messages.stream()
                .collect(Collectors.groupingBy(msg -> 
                    msg.getSenderPhone().equals(currentUserPhone) ? 
                    msg.getReceiverPhone() : msg.getSenderPhone()
                ));

            List<Map<String, Object>> result = new ArrayList<>();
            
            for (Map.Entry<String, List<Messages>> entry : groupedMessages.entrySet()) {
                List<Messages> groupMessages = entry.getValue();
                Messages latestMessage = groupMessages.get(0);
                
                Map<String, Object> group = new HashMap<>();
                // 当前用户永远是发送者，其他用户永远是接收者
                group.put("sender_phone", currentUserPhone);
                group.put("receiver_phone", entry.getKey());
                
                // 如果当前用户是发送者
                if (latestMessage.getSenderPhone().equals(currentUserPhone)) {
                    group.put("sender_name", latestMessage.getSenderName());
                    group.put("sender_avatar", latestMessage.getSenderAvatar());
                    group.put("receiver_name", latestMessage.getReceivername());
                    group.put("receiver_avatar", latestMessage.getReceiverAvatar());
                } else {
                    // 如果当前用户是接收者，交换名字和头像
                    group.put("sender_name", latestMessage.getReceivername());
                    group.put("sender_avatar", latestMessage.getReceiverAvatar());
                    group.put("receiver_name", latestMessage.getSenderName());
                    group.put("receiver_avatar", latestMessage.getSenderAvatar());
                }
                
                // 构建消息数组
                List<Map<String, Object>> messageArray = groupMessages.stream()
                    .map(msg -> {
                        Map<String, Object> message = new HashMap<>();
                        message.put("content", msg.getContent());
                        message.put("time", msg.getTime());
                        return message;
                    })
                    .collect(Collectors.toList());
                
                group.put("content_time_array", messageArray);
                group.put("time", groupMessages.stream()
                    .max(Comparator.comparing(Messages::getTime))
                    .map(Messages::getTime)
                    .orElse(null));
                group.put("message_count", groupMessages.size());
                group.put("unread_count", (int) groupMessages.stream()
                    .filter(msg -> !msg.getIsRead() && msg.getReceiverPhone().equals(currentUserPhone))
                    .count());
                
                result.add(group);
            }
            
            // 按最新消息时间排序
            result.sort((a, b) -> {
                LocalDateTime timeA = (LocalDateTime) a.get("time");
                LocalDateTime timeB = (LocalDateTime) b.get("time");
                return timeB.compareTo(timeA);
            });
            
            return new ResultBody(200, "获取成功", result, result.size());
        }
        return new ResultBody(200, "暂无消息", messages);
    }

    @Override
    public ResultBody getGroupedMessages(Map<String,Object> map) {
        List<Messages> messages = messageMapper.getGroupedMessages(map.get("phone").toString());
        if(!messages.isEmpty()) {
            return new ResultBody(200, "获取成功", messages, messages.size());
        }
        return new ResultBody(200, "暂无消息", messages);
    }

    @Override
    public ResultBody markAsRead(Map<String,Object> map) {
        int result = messageMapper.markAsRead(map.get("phone").toString());
        if(result > 0) {
            return new ResultBody(200, "标记成功", true);
        }
        return new ResultBody(400, "标记失败", false);
    }

    @Override
    public ResultBody batchMarkAsRead(Map<String,Object> map) {
        int result = messageMapper.batchMarkAsRead(map.get("phone").toString());
        if(result > 0) {
            return new ResultBody(200, "标记成功", true);
        }
        return new ResultBody(400, "标记失败", false);
    }

    @Override
    public ResultBody deleteMessage(Map<String,Object> map) {//messageId这个改为接收者的手机号了
        int result = messageMapper.deleteMessage(Long.valueOf(map.get("messageId").toString()), map.get("phone").toString());
        if(result > 0) {
            return new ResultBody(200, "删除成功", true);
        }
        return new ResultBody(400, "删除失败", false);
    }

    @Override
    public ResultBody sendMessage(Map<String,Object> map) {
        // 检查必要参数是否存在
        if (map.get("receiverPhone") == null || map.get("senderPhone") == null || 
            map.get("content") == null || map.get("senderName") == null || 
            map.get("senderAvatar") == null) {
            return new ResultBody(400, "参数不完整", false);
        }

        Messages message = new Messages();
        message.setReceiverPhone(map.get("receiverPhone").toString());
        message.setSenderPhone(map.get("senderPhone").toString());
        message.setContent(map.get("content").toString());
        message.setSenderName(map.get("senderName").toString());
        message.setSenderAvatar(map.get("senderAvatar").toString());
        message.setTime(LocalDateTime.now());
        message.setIsRead(false);
        
        int result = messageMapper.insert(message);
        if(result > 0) {
            return new ResultBody(200, "发送成功", true);
        }
        return new ResultBody(400, "发送失败", false);
    }

    @Override
    public ResultBody getChatMessages(Map<String,Object> map) {
        List<Messages> messages = messageMapper.getChatMessages(
            map.get("senderPhone").toString(), 
            map.get("receiverPhone").toString()
        );
        if(!messages.isEmpty()) {
            return new ResultBody(200, "获取成功", messages, messages.size());
        }
        return new ResultBody(200, "暂无聊天记录", messages);
    }
} 